﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Data;
using System.Reflection;

namespace HJ212_Common
{
    public class DataConvert
    {
        public static DataTable ListToDataTable<T>(List<T> list)
        {
            //创建属性的集合
            List<PropertyInfo> pList = new List<PropertyInfo>();
            //获得反射的入口
            Type type = typeof(T);
            DataTable dt = new DataTable();
            //把所有的public属性加入到集合 并添加DataTable的列
            Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });

            foreach (T t in list)
            {
                DataRow row = dt.NewRow();

                pList.ForEach(p => row[p.Name] = p.GetValue(t, null));

                dt.Rows.Add(row);

            }
            return dt;
        }
        /// <summary>
        /// DataTable 转换为List 集合
        /// </summary>
        /// <typeparam name="TResult">类型</typeparam>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static List<T> DataTableToList<T>(DataTable dt) where T : new()
        {

            //创建返回的集合
            List<T> oblist = new List<T>();

            foreach (DataRow row in dt.Rows)
            {
                //创建TResult的实例
                T ob = new T();
                CopyToEntity(ob, row);
                oblist.Add(ob);
            }
            return oblist;
        }
        /// <summary>
        /// 将entity转换成DataRow
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="adaptedRow"></param>
        public static void CopyToEntity(DataRow adaptedRow, object entity)
        {
            if (entity == null || adaptedRow == null)
            {
                return;
            }
            try
            {
                PropertyInfo[] propertyInfos = entity.GetType().GetProperties();

                List<string> lstCols = new List<string>();
                List<string> lstColsUper = new List<string>();
                foreach (DataColumn col in adaptedRow.Table.Columns)
                {
                    lstCols.Add(col.ColumnName);
                    lstColsUper.Add(col.ColumnName.ToUpper());
                }

                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    try
                    {
                        if (!lstCols.Contains(propertyInfo.Name) && !lstColsUper.Contains(propertyInfo.Name.ToUpper()))
                        {
                            //propertyInfo.SetValue(entity, null, null);
                            continue;
                        }
                        string ColName = lstCols.IndexOf(propertyInfo.Name) >= 0
                                             ? propertyInfo.Name
                                             : lstCols[lstColsUper.IndexOf(propertyInfo.Name.ToUpper())];
                        var obj = propertyInfo.GetValue(entity, null);
                        if (propertyInfo.PropertyType == typeof(decimal?) || propertyInfo.PropertyType == typeof(decimal)
                            || propertyInfo.PropertyType == typeof(double?) || propertyInfo.PropertyType == typeof(double)
                            || propertyInfo.PropertyType == typeof(int?) || propertyInfo.PropertyType == typeof(int))
                        {
                            if (obj == null)
                            {
                                adaptedRow[ColName] = 0;
                            }
                            else
                            {
                                adaptedRow[ColName] = obj;
                            }
                        }
                        else
                        {
                            if (obj == null)
                            {
                                adaptedRow[ColName] = DBNull.Value;
                            }
                            else
                            {
                                adaptedRow[ColName] = obj;
                            }
                        }
                    }
                    finally
                    {

                    }
                }
            }
            catch (Exception ex)
            {
                return;
            }
        }

        /// <summary>
        /// 将entity转换成DataRow
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="adaptedRow"></param>
        public static void DataRowToEntity(DataRow adaptedRow, object entity)
        {
            if (entity == null || adaptedRow == null)
            {
                return;
            }
            try
            {
                PropertyInfo[] propertyInfos = entity.GetType().GetProperties();

                List<string> lstCols = new List<string>();
                List<string> lstColsUper = new List<string>();
                foreach (DataColumn col in adaptedRow.Table.Columns)
                {
                    lstCols.Add(col.ColumnName);
                    lstColsUper.Add(col.ColumnName.ToUpper());
                }

                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    try
                    {
                        if (!lstCols.Contains(propertyInfo.Name) && !lstColsUper.Contains(propertyInfo.Name.ToUpper()))
                        {
                            //propertyInfo.SetValue(entity, null, null);
                            continue;
                        }
                        string ColName = lstCols.IndexOf(propertyInfo.Name) >= 0
                                             ? propertyInfo.Name
                                             : lstCols[lstColsUper.IndexOf(propertyInfo.Name.ToUpper())];
                        var obj = propertyInfo.GetValue(entity, null);
                        if (propertyInfo.PropertyType == typeof(decimal?) || propertyInfo.PropertyType == typeof(decimal)
                            || propertyInfo.PropertyType == typeof(double?) || propertyInfo.PropertyType == typeof(double)
                            || propertyInfo.PropertyType == typeof(int?) || propertyInfo.PropertyType == typeof(int))
                        {
                            if (obj == null)
                            {
                                adaptedRow[ColName] = 0;
                            }
                            else
                            {
                                adaptedRow[ColName] = obj;
                            }
                        }
                        else
                        {
                            adaptedRow[ColName] = obj;
                        }
                    }
                    finally
                    {

                    }
                }
            }
            catch (Exception ex)
            {
                return;
            }
        }

        /// <summary>
        /// 将DataRow转换成相应的对象
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="adaptedRow"></param>
        public static void CopyToEntity(object entity, DataRow adaptedRow)
        {
            if (entity == null || adaptedRow == null)
            {
                return;
            }
            PropertyInfo[] propertyInfos = entity.GetType().GetProperties();

            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                if (!CanSetPropertyValue(propertyInfo, adaptedRow))
                {
                    continue;
                }

                try
                {
                    if (adaptedRow[propertyInfo.Name] is DBNull)
                    {
                        propertyInfo.SetValue(entity, null, null);
                        continue;
                    }
                    SetPropertyValue(entity, adaptedRow, propertyInfo);
                }
                finally
                {

                }
            }
        }

        private static bool CanSetPropertyValue(PropertyInfo propertyInfo, DataRow adaptedRow)
        {
            if (!propertyInfo.CanWrite)
            {
                return false;
            }

            if (!adaptedRow.Table.Columns.Contains(propertyInfo.Name))
            {
                return false;
            }

            return true;
        }

        private static void SetPropertyValue(object entity, DataRow adaptedRow, PropertyInfo propertyInfo)
        {
            if (propertyInfo.PropertyType == typeof(DateTime?) ||
                propertyInfo.PropertyType == typeof(DateTime))
            {
                DateTime date = DateTime.MaxValue;
                DateTime.TryParse(adaptedRow[propertyInfo.Name].ToString(),
                    CultureInfo.CurrentCulture, DateTimeStyles.None, out date);

                propertyInfo.SetValue(entity, date, null);
            }
            else if (propertyInfo.PropertyType == typeof(int?) ||
                propertyInfo.PropertyType == typeof(int) ||
                propertyInfo.PropertyType == typeof(Int32?) ||
                propertyInfo.PropertyType == typeof(Int32)
                )
            {
                propertyInfo.SetValue(entity, TypeParser.StrToInt(adaptedRow[propertyInfo.Name].ToString()), null);
            }
            else if (
                            propertyInfo.PropertyType == typeof(Int64?) ||
                            propertyInfo.PropertyType == typeof(Int64)
                            )
            {
                propertyInfo.SetValue(entity, TypeParser.StrToInt64(adaptedRow[propertyInfo.Name].ToString()), null);
            }
            else
            {
                propertyInfo.SetValue(entity, adaptedRow[propertyInfo.Name], null);
            }
        }


        /// <summary>
        /// 将集合类转换成DataTable
        /// </summary>
        /// <param name="list">集合</param>
        /// <returns></returns>
        public static DataTable ToDataTable(IList list)
        {
            DataTable result = new DataTable();
            if (list.Count > 0)
            {
                PropertyInfo[] propertys = list[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    result.Columns.Add(pi.Name, pi.PropertyType);
                }

                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(list[i], null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }

        /// <summary>
        /// 将泛型集合类转换成DataTable
        /// </summary>
        /// <typeparam name="T">集合项类型</typeparam>
        /// <param name="list">集合</param>
        /// <returns>数据集(表)</returns>
        public static DataTable ToDataTable<T>(IList<T> list)
        {
            return ToDataTable<T>(list, null);
        }

        /// <summary>
        /// 将泛型集合类转换成DataTable
        /// </summary>
        /// <typeparam name="T">集合项类型</typeparam>
        /// <param name="list">集合</param>
        /// <param name="propertyName">需要返回的列的列名</param>
        /// <returns>数据集(表)</returns>
        public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
        {
            List<string> propertyNameList = new List<string>();
            if (propertyName != null)
                propertyNameList.AddRange(propertyName);

            DataTable result = new DataTable();
            if (list.Count > 0)
            {
                PropertyInfo[] propertys = list[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    if (propertyNameList.Count == 0)
                    {
                        result.Columns.Add(pi.Name, pi.PropertyType);
                    }
                    else
                    {
                        if (propertyNameList.Contains(pi.Name))
                            result.Columns.Add(pi.Name, pi.PropertyType);
                    }
                }

                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        if (propertyNameList.Count == 0)
                        {
                            object obj = pi.GetValue(list[i], null);
                            tempList.Add(obj);
                        }
                        else
                        {
                            if (propertyNameList.Contains(pi.Name))
                            {
                                object obj = pi.GetValue(list[i], null);
                                tempList.Add(obj);
                            }
                        }
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }



    }
}
